package com.sx.shop.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sx.shop.entity.Category;
import com.sx.shop.mapper.CategoryMapper;
import com.sx.shop.mapper.ProductMapper;
import com.sx.shop.vo.CategoryTreeVo;
import com.sx.shop.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryService
{
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;
    @Transactional
    public String addCateGory(Integer pId, String name)
    {
            if(name==null) return "操作有误";
            if(pId==null) pId=0;
            if(categoryMapper.addCateGory(pId,name)==1)
            {
                return "添加成功";
            }else{
                return "添加失败，请重试";
            }
    }
    public ResultVo selectCateGory(String keyword, Integer page , Integer limit) {
        // TODO Auto-generated method stub
        ResultVo vo = new ResultVo();

        PageHelper.startPage( page , limit);//代码下的第一个查询，有分页效果
        List<Category> list = categoryMapper.selectCategory(keyword);
        PageInfo<Category> pageInfo = new PageInfo<>(list);
        vo.setData(pageInfo.getList());
        vo.setCount(pageInfo.getTotal());
        return vo;
    }
    public String doSave(Category category)
    {
        if(category.getId()==null)
        {
            if(categoryMapper.addCateGory(category.getParent_id(),category.getName())==1)
                return "操作成功";
        }else {
            if(categoryMapper.updateCateGory(category)==1)
                return "操作成功";
        }
        return "操作失败";
    }
    @Transactional
    public String doDel(Integer id)
    {
        if(id==null) return "操作失败";
        //查询一下有没有商品用到这个id了或者用到它的子Id了？
        if(!categoryMapper.selectByParentId(id).isEmpty())
            return "删除失败，请删除它的子类";
        if(!productMapper.findByCategory(id).isEmpty())
            return "有属于此类的商品，删除失败";
        categoryMapper.delete(id);
        return "删除成功";
    }
    public Category selectById(Integer id)
    {
        return categoryMapper.selectById(id);
    }
    public List<Category>selectByParentId(Integer pId)
    {
        return categoryMapper.selectByParentId(pId);
    }
    public List<CategoryTreeVo> selectCategoryTree(Integer productId)
    {

        return categoryMapper.selectCategoryTree(productId);
    }

}
